<template>
  <div ref="gauge" :style="{width: '100%', height: '350px'}"></div>
</template>

<script setup name="Dashboard">
import * as echarts from 'echarts';
import { getCurrentFlow } from '@/api/coal/realtimeData';
//import 'echarts-gl';

const gauge = shallowRef({})
const myChart = shallowRef({})

let flushDashboard = ref<String>("");

const props = defineProps({
  deviceId: {
    type: Number,
    default: null,
  },
})

const selfXData = ref(0)

onMounted(() => {
  nextTick(() => {
    const resizeOb = new ResizeObserver((entries) => {
      for (const entry of entries) {
        echarts.getInstanceByDom(entry.target).resize();
      }
    })
    resizeOb.observe(gauge.value)
    initChart()
    //随着屏幕大小调节图表
    window.addEventListener("resize", () => {
      myChart.value.resize();
    });
    flushDashboard = setInterval(()=>{
      // 根据设备id查询瞬时量
      //const random = +(Math.random() * 600).toFixed(2);
      initCharData().then(resp=>{
        myChart.value.setOption({
          series: [
            {
              data: [
                {
                  value: selfXData.value
                }]
            },]
        })
      })
    },1000*5)
  })
})

function initCharData(){
  return getCurrentFlow(props.deviceId).then(resp=>{
    if(resp.data && resp.data.dataValue){
      selfXData.value = parseFloat(resp.data.dataValue).toFixed(2)
    } else {
      selfXData.value = 0
    }
  })
}

function initChart() {
  nextTick(() => {
    myChart.value = echarts.init(gauge.value);
    initCharData().then(resp=>{
      initOption();
    })
  })
}

function initOption(){
  let option = {
    title: {
      text: '单位：吨/小时',
    },
    tooltip: {
      formatter: '{a} <br/> {c} {b}'+'吨/小时',
    },
    series: [
      {
        name: '煤流瞬时图',
        type: 'gauge',
        axisLine: {
          lineStyle: {
            width: 10,
            color: [
              [0.4, '#67e0e3'],
              [0.8, '#37a2da'],
              [1, '#fd666d']
            ]
          }
        },
        pointer: {
          itemStyle: {
            color: 'inherit'
          }
        },
        axisTick: {
          distance: -30,
          length: 8,
          lineStyle: {
            color: '#fff',
            width: 0
          }
        },
        splitLine: {
          distance: -30,
          length: 30,
          lineStyle: {
            color: '#fff',
            width: 4
          }
        },
        detail: {
          valueAnimation: true,
          formatter: '{value}',
          color: 'inherit'
        },
        data: [
          {
            value: selfXData.value,
          }
        ],
        max: 5000
      }
    ]
  };
  myChart.value.setOption(option)
}
onBeforeUnmount(() => {
  clearInterval(flushDashboard)
})
</script>
